import Api from '../api'


const offiaccount = {
	login: (qrCodeCallback) => {
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'POST',
				url: Api.offiaccount.login,
				success(res) {
					if (res.data.code === Api.Code.Success) {
						qrCodeCallback(res.data)
						let checkLogin = function(unique) {
							uni.request({
								method: 'GET',
								url: Api.offiaccount.checkLogin + '?unique=' + res.data.data.unique,
								success(innerRes) {
									if (innerRes.data.code === Api.Code.Success) {
										resolve(innerRes.data)
									} else {
										console.log('等待扫码.')
										setTimeout(checkLogin, 2000)
									}
								},
								fail(err) {
									console.log('公众号二维码获取失败', err)
									reject('公众号二维码获取失败')
								}
							})
						}
						checkLogin()
					} else {
						console.log('公众号二维码获取失败', err)
						reject('公众号二维码获取失败')
					}
				},
				fail(err) {
					console.log('公众号二维码获取网络异常', err)
					reject('公众号二维码获取网络异常')
				}
			})
		})
	}
}

export default offiaccount
